//
//  UrbanPrinterViewController.m
//  UrbanManagement
//
//  Created by Can on 2018/4/18.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "UrbanPrinterViewController.h"
#import "UrbanPrinterTableViewCell.h"
#import "UrbanBlueTooth.h"
#import "UrbanMainViewController.h"

@interface UrbanPrinterViewController ()<UITableViewDelegate,UITableViewDataSource,CBCentralManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (strong, nonatomic) UrbanBlueTooth *bluetooth;
@property (strong, nonatomic) CBPeripheral *peripheral;
@property (strong, nonatomic) NSMutableArray *listDevices;
@property (nonatomic, strong) NSIndexPath *lastIndex;

@property (strong, nonatomic) CBCentralManager *centralManager;

@end

@implementation UrbanPrinterViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self creatNav];
    
    self.listDevices = [NSMutableArray array];
    self.bluetooth = [[UrbanBlueTooth alloc]init];
    
    [self creatTableView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self initTitleWithTitle:@"选择设备"];
    
    self.centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:nil];
}

//开始查看服务, 蓝牙开启
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            _BlueToothManagerState = UrbanBlueToothManagerStateIsOpen;
            [self BlueState:1];
            break;
            
        case CBManagerStatePoweredOff:
            _BlueToothManagerState = UrbanBlueToothManagerStateUnopened;
            [ToolViewVC addKeyAlterViewController:@"蓝牙未打开，请打开蓝牙" Controller:self];
            break;
            
        case CBManagerStateUnauthorized:
            _BlueToothManagerState = UrbanBlueToothManagerStateWantAuthority;
            [ToolViewVC addKeyAlterViewController:@"蓝牙未授权" Controller:self];
            break;
            
        case CBManagerStateUnsupported:
            _BlueToothManagerState = UrbanBlueToothManagerStateNotSupported;
            [ToolViewVC addKeyAlterViewController:@"设备不支持蓝牙" Controller:self];
            break;
            
        case CBManagerStateResetting:
            _BlueToothManagerState = UrbanBlueToothManagerStateResetting;
            [ToolViewVC addKeyAlterViewController:@"蓝牙重置状态" Controller:self];
            break;
            
        case CBManagerStateUnknown:
            _BlueToothManagerState = UrbanBlueToothManagerStateInitialization;
            [ToolViewVC addKeyAlterViewController:@"蓝牙处于未知状态" Controller:self];
            break;
            
        default:
            break;
    }
}

//导航栏按钮
- (void)creatNav
{
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn addTarget:self action:@selector(printBtn) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"搜索" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn sizeToFit];
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    self.navigationItem.rightBarButtonItem  = rightBtnItem;
}

- (void)onTapLeftBarButton
{
    for (UIViewController *controller in self.navigationController.viewControllers){
        if ([controller isKindOfClass:[UrbanMainViewController class]]) {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}

- (void)creatTableView{
    CGFloat height = NavBarHeight;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH - 15*screenW_6 - 45*screenW_6 - height) style:UITableViewStylePlain];
    _tableView.backgroundColor = Color(247, 247, 247);
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = 0;
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    //打印
    UIButton *printer = [TomamaUI createButton:0 Frame:CGRectMake(15*screenW_6, SCREENH - 15*screenW_6 - 45*screenW_6 - height, SCREENW - 30*screenW_6, 45*screenW_6) targ:self sel:@selector(print) titleColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:16*screenW_6] title:@"确定" image:nil backGroundImage:@"blue_button2"];
    printer.layer.cornerRadius = 3*screenW_6;
    printer.layer.masksToBounds = YES;
    [self.view addSubview:printer];
}

#pragma mark - tabledelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _listDevices.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

//section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;//section头部高度
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UrbanPrinterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PrinterCell"];
    if (!cell) {
        cell = [[UrbanPrinterTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PrinterCell"];
    }

    NSString* uuid = [NSString stringWithFormat:@"%@", [[_listDevices objectAtIndex:indexPath.section] identifier]];
    uuid = [uuid substringFromIndex:[uuid length] - 12];

    cell.name.text = [[_listDevices objectAtIndex:indexPath.section] name];
    cell.model.text = uuid;
    
    if ([[Storage getPrinter] isEqualToString:uuid]) {
        [cell.choseBtn setImage:[UIImage imageNamed:@"selected_blue"] forState:UIControlStateNormal];
        self.peripheral = [_listDevices objectAtIndex:indexPath.section];
        _lastIndex = indexPath;
    }else{
        [cell.choseBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
    }
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.peripheral = [_listDevices objectAtIndex:indexPath.section];

    //当前cell row
    NSInteger newRow = [indexPath section];
    //记录上一次cell row
    NSInteger oldRow = (_lastIndex != nil) ? [_lastIndex section] : -1;
//    NSInteger oldRow = _lastIndex.section;

    if (newRow != oldRow)
    {
        //选中cell
        UrbanPrinterTableViewCell *newcell =  [tableView cellForRowAtIndexPath:indexPath];
        [newcell.choseBtn setImage:[UIImage imageNamed:@"selected_blue"] forState:UIControlStateNormal];
        //取消上一次选中cell
        UrbanPrinterTableViewCell *oldCell = [tableView cellForRowAtIndexPath:_lastIndex];
        [oldCell.choseBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
    }
    _lastIndex = indexPath;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50*screenW_6;
}

- (void)printBtn
{
    [self BlueState:1];
}

- (void)wrapPrintDatas
{
    [self.bluetooth StartPage:560 pageHeight:888 ];
    [self.bluetooth TextCenter:@"违法停车告知单" font:24 x:125 y:20];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"编    号:%@",_orderNumber] font:24 x:30 y:90];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆牌号:%@",_plateNumber] font:24 x:30 y:130];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆类型:%@",_carType] font:24 x:30 y:170];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"号牌颜色:%@",_numPlateColor] font:24 x:30 y:210];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放时间:%@",_parkTime] font:24 x:30 y:250];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放地点:%@",_address] font:24 x:30 y:290];
    [self.bluetooth TextLeft:@"   上述时间、地点，该机动车未在停车场或道路" font:24 x:30 y:350];
    [self.bluetooth TextLeft:@"停车泊位内停放，违反了《中华人民共和国道路安" font:24 x:30 y:390];
    [self.bluetooth TextLeft:@"全交通法》第56条的规定，违法行为已被拍照取证" font:24 x:30 y:430];
    [self.bluetooth TextLeft:@"。根据《湖北省实施<中华人民共和国道路交通安" font:24 x:30 y:470];
    [self.bluetooth TextLeft:@"全法>办法》第69条第十三项的规定，请自收到本" font:24 x:30 y:510];
    [self.bluetooth TextLeft:@"告知单5日内到西湖一路33号市城管执法局一楼服" font:24 x:30 y:550];
    [self.bluetooth TextLeft:@"务大厅接受处理。" font:24 x:30 y:590];
    [self.bluetooth TextLeft:[self getTimes] font:24 x:380 y:650];
    [self.bluetooth zp_darwQRCode:30 y:650 unit_width:4 text:@"https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI2MTQ0MDA2Mg=="];
    [self.bluetooth TextLeft:@"关注“东坡城曦”" font:24 x:30 y:805];
    
    [self.bluetooth end];
}

- (void)wrapPrintJinGaoDatas
{
    [self.bluetooth StartPage:560 pageHeight:888 ];
    [self.bluetooth TextCenter:@"温 馨 提 示" font:24 x:125 y:20];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"编    号:%@",_orderNumber] font:24 x:30 y:90];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆牌号:%@",_plateNumber] font:24 x:30 y:130];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆类型:%@",_carType] font:24 x:30 y:170];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"号牌颜色:%@",_numPlateColor] font:24 x:30 y:210];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放时间:%@",_parkTime] font:24 x:30 y:250];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放地点:%@",_address] font:24 x:30 y:290];
    [self.bluetooth TextLeft:@"   上述时间、地点，该机动车未在停车场或道路" font:24 x:30 y:350];
    [self.bluetooth TextLeft:@"停车泊位内停放，请您看到提示后迅速将车辆转移" font:24 x:30 y:390];
    [self.bluetooth TextLeft:@"到规定地点停放。" font:24 x:30 y:430];
    [self.bluetooth TextLeft:@"   节日期间，为了您有一个愉快的心情，本次不" font:24 x:30 y:470];
    [self.bluetooth TextLeft:@"予处罚，如再次违停将依法处罚，请您理解，支持" font:24 x:30 y:510];
    [self.bluetooth TextLeft:@"和配合，祝您快乐！" font:24 x:30 y:550];
    [self.bluetooth TextLeft:[self getTimes] font:24 x:380 y:610];
    [self.bluetooth zp_darwQRCode:30 y:610 unit_width:4 text:@"https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI2MTQ0MDA2Mg=="];
    [self.bluetooth TextLeft:@"关注“东坡城曦”" font:24 x:30 y:765];
    
    [self.bluetooth end];
}

- (NSString *)getTimes
{
    // 日期格式化类
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    // 设置日期格式(为了转换成功)
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    // NSString * -> NSDate *
    NSDate *date = [fmt dateFromString:_parkTime];
    
    // 利用NSCalendar处理日期
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *cmps = [calendar components:unit  fromDate:date];
    
    NSString *time = [NSString stringWithFormat:@"%ld年%ld月%ld日",(long)cmps.year,(long)cmps.month,(long)cmps.day];
    
    return time;
}

- (void)print{
    
    /* Byte byte[] = {0x0d,0x0a};
     NSData *adata = [[NSData alloc] initWithBytes:byte length:2];
     [self.bluetooth open:self.peripheral];
     [self.bluetooth flushRead];
     [self.bluetooth writeData:adata];
     [self.bluetooth close];
     */
    
    if (self.peripheral) {
        NSString* uuid = [NSString stringWithFormat:@"%@", [[_listDevices objectAtIndex:_lastIndex.section] identifier]];
        uuid = [uuid substringFromIndex:[uuid length] - 12];
        
        [standfault setObject:uuid forKey:@"Printer"];
        [standfault synchronize];
        
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [ToolViewVC addKeyAlterViewController:@"请选择打印机" Controller:self];
    }
    
//    if (self.peripheral) {
//        [self BlueState:0];
//    }else{
//        [ToolViewVC addKeyAlterViewController:@"请选择打印机" Controller:self];
//    }
}

-(void)sendPrintData{
    
    int r = self.bluetooth.dataLength;
    
    NSData *data = [self.bluetooth getData:r];
    
    [self.bluetooth writeData:data];
}

- (void)BlueState:(NSInteger)num
{
    switch (_BlueToothManagerState) {
        case UrbanBlueToothManagerStateIsOpen:{
            if (num == 0) {
                [self.bluetooth open:self.peripheral];
                [self.bluetooth flushRead];
                
                if ([_flag integerValue] == 3) {
                    [self wrapPrintJinGaoDatas];
                }else{
                    [self wrapPrintDatas];
                }
                [self sendPrintData];
                [self.bluetooth reset];
                [self.bluetooth close];
                
            }else{
                if(_listDevices != nil){
                    _listDevices = nil;
                    _listDevices = [NSMutableArray array];
                    [_tableView reloadData];
                }
                
                BLOCK_CALLBACK_SCAN_FIND callback =
                ^( CBPeripheral*peripheral)
                {
                    [self.listDevices addObject:peripheral];
                    NSLog(@"scan find: %@",self.listDevices );
                    
                    NSMutableArray *listAry = [[NSMutableArray alloc]init];
                    for (NSString *str in self.listDevices) {
                        if (![listAry containsObject:str]) {
                            [listAry addObject:str];
                        }
                    }
                    
                    for (int i = 0; i < listAry.count; i++) {
                        if (![[listAry objectAtIndex:i] name]) {
                            [listAry removeObjectAtIndex:i];
                        }
                    }
                    
                    self.listDevices = listAry;
                    
                    NSLog(@"scan find: %@",self.listDevices );
                    
                    [self->_tableView reloadData];
                };
                
                [self.bluetooth scanStart:callback];
                
                double delayInSeconds = 5.0;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds* NSEC_PER_SEC));
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    [self.bluetooth scanStop];
                });
            }
            
        }
            break;
            
        case UrbanBlueToothManagerStateUnopened:
            
            [ToolViewVC addKeyAlterViewController:@"蓝牙未打开，请打开蓝牙" Controller:self];
            break;
            
        case UrbanBlueToothManagerStateWantAuthority:
            
            [ToolViewVC addKeyAlterViewController:@"蓝牙未授权" Controller:self];
            break;
            
        case UrbanBlueToothManagerStateNotSupported:
            
            [ToolViewVC addKeyAlterViewController:@"设备不支持蓝牙" Controller:self];
            break;
            
        case UrbanBlueToothManagerStateResetting:
            
            [ToolViewVC addKeyAlterViewController:@"蓝牙重置状态" Controller:self];
            break;
            
        case UrbanBlueToothManagerStateInitialization:
            
            [ToolViewVC addKeyAlterViewController:@"蓝牙处于未知状态" Controller:self];
            break;
            
        default:
            break;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
